package com.fakesmoker.aidawnda.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fakesmoker.aidawnda.annotation.AuthCheck;
import com.fakesmoker.aidawnda.common.BaseResponse;
import com.fakesmoker.aidawnda.common.DeleteRequest;
import com.fakesmoker.aidawnda.common.ErrorCode;
import com.fakesmoker.aidawnda.common.ResultUtils;
import com.fakesmoker.aidawnda.constant.UserConstant;
import com.fakesmoker.aidawnda.exception.BusinessException;
import com.fakesmoker.aidawnda.exception.ThrowUtils;
import com.fakesmoker.aidawnda.model.dto.usertag.UserTagAddRequest;
import com.fakesmoker.aidawnda.model.dto.usertag.UserTagEditRequest;
import com.fakesmoker.aidawnda.model.dto.usertag.UserTagQueryRequest;
import com.fakesmoker.aidawnda.model.dto.usertag.UserTagUpdateRequest;
import com.fakesmoker.aidawnda.model.entity.User;
import com.fakesmoker.aidawnda.model.entity.UserTag;
import com.fakesmoker.aidawnda.model.vo.UserTagVO;
import com.fakesmoker.aidawnda.service.UserTagService;
import com.fakesmoker.aidawnda.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 用户回用户标签表接口
 *
 * @author lcy
 */
@RestController
@RequestMapping("/userTag")
@Slf4j
public class UserTagController {

    @Resource
    private UserTagService userTagService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建用户回用户标签表
     *
     * @param userTagAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addUserTag(@RequestBody UserTagAddRequest userTagAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(userTagAddRequest == null, ErrorCode.PARAMS_ERROR);
        UserTag userTag = new UserTag();
        BeanUtils.copyProperties(userTagAddRequest, userTag);
        // 数据校验
        userTagService.validUserTag(userTag, true);
        User loginUser = userService.getLoginUser(request);
        userTag.setUserId(loginUser.getId());
        // 写入数据库
        boolean result = userTagService.save(userTag);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newUserTagId = userTag.getId();
        return ResultUtils.success(newUserTagId);
    }

    /**
     * 删除用户回用户标签表
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUserTag(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        UserTag oldUserTag = userTagService.getById(id);
        ThrowUtils.throwIf(oldUserTag == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldUserTag.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = userTagService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新用户回用户标签表（仅管理员可用）
     *
     * @param userTagUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateUserTag(@RequestBody UserTagUpdateRequest userTagUpdateRequest) {
        if (userTagUpdateRequest == null || userTagUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserTag userTag = new UserTag();
        BeanUtils.copyProperties(userTagUpdateRequest, userTag);
        // 数据校验
        userTagService.validUserTag(userTag, false);
        // 判断是否存在
        long id = userTagUpdateRequest.getId();
        UserTag oldUserTag = userTagService.getById(id);
        ThrowUtils.throwIf(oldUserTag == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = userTagService.updateById(userTag);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取用户回用户标签表（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<UserTagVO> getUserTagVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        UserTag userTag = userTagService.getById(id);
        ThrowUtils.throwIf(userTag == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(userTagService.getUserTagVO(userTag, request));
    }

    /**
     * 分页获取用户回用户标签表列表（仅管理员可用）
     *
     * @param userTagQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<UserTag>> listUserTagByPage(@RequestBody UserTagQueryRequest userTagQueryRequest) {
        long current = userTagQueryRequest.getCurrent();
        long size = userTagQueryRequest.getPageSize();
        // 查询数据库
        Page<UserTag> userTagPage = userTagService.page(new Page<>(current, size),
                userTagService.getQueryWrapper(userTagQueryRequest));
        return ResultUtils.success(userTagPage);
    }

    /**
     * 分页获取用户回用户标签表列表（封装类）
     *
     * @param userTagQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<UserTagVO>> listUserTagVOByPage(@RequestBody UserTagQueryRequest userTagQueryRequest,
                                                               HttpServletRequest request) {
        long current = userTagQueryRequest.getCurrent();
        long size = userTagQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<UserTag> userTagPage = userTagService.page(new Page<>(current, size),
                userTagService.getQueryWrapper(userTagQueryRequest));
        // 获取封装类
        return ResultUtils.success(userTagService.getUserTagVOPage(userTagPage, request));
    }

    /**
     * 分页获取当前登录用户创建的用户回用户标签表列表
     *
     * @param userTagQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<UserTagVO>> listMyUserTagVOByPage(@RequestBody UserTagQueryRequest userTagQueryRequest,
                                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(userTagQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        userTagQueryRequest.setUserId(loginUser.getId());
        long current = userTagQueryRequest.getCurrent();
        long size = userTagQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<UserTag> userTagPage = userTagService.page(new Page<>(current, size),
                userTagService.getQueryWrapper(userTagQueryRequest));
        // 获取封装类
        return ResultUtils.success(userTagService.getUserTagVOPage(userTagPage, request));
    }

    /**
     * 编辑用户回用户标签表（给用户使用）
     *
     * @param userTagEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editUserTag(@RequestBody UserTagEditRequest userTagEditRequest, HttpServletRequest request) {
        if (userTagEditRequest == null || userTagEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        UserTag userTag = new UserTag();
        BeanUtils.copyProperties(userTagEditRequest, userTag);
        // 数据校验
        userTagService.validUserTag(userTag, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = userTagEditRequest.getId();
        UserTag oldUserTag = userTagService.getById(id);
        ThrowUtils.throwIf(oldUserTag == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldUserTag.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = userTagService.updateById(userTag);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    // endregion
}
